import axios from 'axios'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: "http://localhost",
  // baseURL: "http://1.13.198.191:8082",
  timeout: 150000, // request timeout
  withCredentials: true,// 允许跨域请求携带 cookie
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['Token'] = getToken();
      // // headers不支持中文参数
      // config.headers['User'] = localStorage.getItem('User')

    }
     // 保留自定义的 Content-Type
    //  if (!config.headers['Content-Type']) {
    //   config.headers['Content-Type'] = 'application/json';
    // }
    // console.log(config);
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // console.log(res);
    // 文件流没有错误码 只有data 所以要放在res.Code前面判断 直接return data
    if (response.request.responseType && response.request.responseType.toLowerCase() === 'arraybuffer'||!res.Code) {
      return res
    }
    if (res.Code != 200) {
      Message({
        message: res.Msg || '出现错误',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.Code === 401) {
        // to re-login
        MessageBox.confirm('请重新登录', '登录失效', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetState').then(() => {
            // location.reload()
            console.log('location');
            router.push({ name: 'Login' });
          })
        })
      }
      // return Promise.reject(new Error(res.Msg || '出现错误'))
      return Promise.reject(res.Msg)
    } else {
      // console.log(res);
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.Msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
